


#include <vector>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <iterator>

#include "split.h"


using namespace std;

static string& trim(string &line)
{
	if(line.empty())
	{
		return line;
	}

	line.erase(0, line.find_first_not_of(" \t"));
	line.erase(line.find_last_not_of(" \t") + 1);
	return line;
}

static int Split2Vector(vector<string> &vect, const string &line, const string &delim)
{
	int start = 0;
	int end = 0;
	
	while(true)
	{
		end = line.find_first_of(delim.c_str(), start);
		if(string::npos == end)
		{
			string tmp = line.substr(start);
			tmp = trim(tmp);
			if(!tmp.empty())
			{
				vect.push_back(tmp);
			}
			break;
		}
		else
		{
			string tmp = line.substr(start, end-start);
			start = end+1;
			tmp = trim(tmp);
			if(!tmp.empty())
			{
				vect.push_back(tmp);
			}
		}
	}

	//copy(vect.begin(), vect.end(), ostream_iterator<string>(cout, ","));
	return 0;
}


Split::Split(DataSum *DS, const int keyindex, const string delim)
:m_nKeyIndex(keyindex),m_pDS(DS),m_strDelim(delim)
{

}

int Split::SplitLine(const string &line)
{
	vector<string>  vect;
	Split2Vector(vect, line, m_strDelim);

	if(m_nKeyIndex >= vect.size())
		return -1;

	const string &Key = vect[m_nKeyIndex-1];	
	for(int i = 0; i < vect.size(); ++i)
	{
		if(i == (m_nKeyIndex-1))
			continue;
		
		const string tmp = vect[i];
		if(!tmp.empty())
		{
			long val = strtol(tmp.c_str(), NULL, 10);
			m_pDS->add(Key, i+1, val);
		}
	}

	return 0;
}


#ifdef TEST_SPLIT

#include <iostream>

#include "output.h"
#include "position.h"
#include "sum.h"

int main()
{
#if 0
	vector<string>  vect;
	string line = "henry:x:525:525::/data/henry:/bin/bash";
	string delim = ":";

	std::cout<<line<<std::endl;
	Split2Vector(vect, line, delim);
	for(int i = 0; i < vect.size(); ++i)
		std::cout<<"["<<vect[i]<<"]";
	std::cout<<std::endl;	
#else
	Position pos0;
	pos0.add(2);	
	pos0.add(3);	
	DataSum ds(pos0);

	//Output  *pcsv_output = new CSVOutput(pos0.size());
	CSVOutput csv_output(pos0.size());

	string line[] = {
		"henry:1000#200",
		"henry:1000#200",
		"henry:1000#200",
		"beijing:1000#200",
		"henry:1000#200"
	};
	string delim = ":#";

	Split  sp(&ds,1,delim);
	for(int i = 0; i < 5; ++i)
		sp.SplitLine(line[i]);

	ds.flush(csv_output);
	
#endif

	return 0;
}

#endif
